package com.example.bingwallpaper.ui

import android.Manifest
import android.content.ContentValues
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.PixelCopy.request
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.DragAndDropPermissionsCompat.request
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.example.bingwallpaper.BingWallpaperApplication
import com.example.bingwallpaper.R
import com.permissionx.guolindev.PermissionX
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.security.Permission


class MainActivity : AppCompatActivity() {

    lateinit var viewModel: MainViewModel


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
        setContentView(R.layout.activity_main)

        textView.visibility = View.INVISIBLE
        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
        viewModel.currentImage.observe(this, Observer {
            setImage(it.url)
            textView.text = viewModel.currentImage.value?.copyright
        })
        viewModel.getImageUrl()

        imageView.setOnClickListener {
            when (textView.visibility) {
                View.INVISIBLE -> textView.visibility = View.VISIBLE
                View.VISIBLE -> textView.visibility = View.INVISIBLE
            }

        }

        imageView.setOnLongClickListener {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
                PermissionX.init(this)
                    .permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                    .request { allGranted, grantedList, deniedList ->
                        if (allGranted) {
                            val bitmap = (imageView.drawable as BitmapDrawable).bitmap
                            val displayName = "${viewModel.currentImage.value?.copyright?.split(" ")?.get(0)}.jpg"
                            val mimeType = "image/jpeg"
                            val compressFormat = Bitmap.CompressFormat.JPEG
                            addBitmapToAlbum(bitmap, displayName, mimeType, compressFormat)
                        } else {
                            Toast.makeText(this, "您拒绝了如下权限：$deniedList", Toast.LENGTH_SHORT)
                                .show()
                        }
                    }
            } else {
                val bitmap = (imageView.drawable as BitmapDrawable).bitmap
                val displayName = "${viewModel.images.value?.get(0)?.copyright?.split(" ")?.get(0)}.jpg"
                val mimeType = "image/jpeg"
                val compressFormat = Bitmap.CompressFormat.JPEG
                addBitmapToAlbum(bitmap, displayName, mimeType, compressFormat)
            }

            true
        }
        
    }

    fun setImage(url: String) {
        Glide.with(BingWallpaperApplication.context)
                .load(url)
                .placeholder(R.drawable.load)
                .into(imageView)
    }

    private fun addBitmapToAlbum(bitmap: Bitmap, displayName: String, mimeType: String, compressFormat: Bitmap.CompressFormat) {
        val values = ContentValues()
        values.put(MediaStore.MediaColumns.DISPLAY_NAME, displayName)
        values.put(MediaStore.MediaColumns.MIME_TYPE, mimeType)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM)
        } else {
            values.put(MediaStore.Images.ImageColumns.DATA, "${Environment.getExternalStorageDirectory().path}/${Environment.DIRECTORY_DCIM}/$displayName");
        }
        val uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
        if (uri != null) {
            val outputStream = contentResolver.openOutputStream(uri)
            if (outputStream != null) {
                bitmap.compress(compressFormat, 100, outputStream)
                outputStream.close()
                Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show()
            }
        }
    }



    
}